package vcsn.entities;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

import vcsn.Config;

public class FileLock {
	private String lockFileLocation;
	
	public FileLock(String lockFilePath){
		lockFileLocation =lockFilePath;
	}
	
	public HashMap<String, String> getlockedPair(){
		HashMap<String, String> lockPairList = new HashMap<String, String>();
		List<String> lockedFileList = readLockedFileList();
		for(String str : lockedFileList){
			lockPairList.put(str.split(Config.separator)[0], str.split(Config.separator)[1]);
		}
		return lockPairList;
	}
	
	public HashMap<String, String> getlockedPair(String lockFilePath){
		HashMap<String, String> lockPairList = new HashMap<String, String>();
		List<String> lockedFileList = readLockedFileList(lockFilePath);
		for(String str : lockedFileList){
			lockPairList.put(str.split(Config.separator)[0], str.split(Config.separator)[1]);
		}
		return lockPairList;
	}
	
	public List<String> readLockedFileList(){
//		File lockfile = new File(lockFileLocation);
//		Scanner sc;
//		try {
//			sc = new Scanner(lockfile);
//		
//		List<String> lockedFileList = new ArrayList<String>();
//		while(sc.hasNextLine()){
//			lockedFileList.add(sc.nextLine());
//		}
//		sc.close();
//		return lockedFileList;
//		}catch (Exception e){
//			e.printStackTrace();
//			return null;
//		}
		List<String> lockedFileList = readLockedFileList(lockFileLocation);
		return lockedFileList;
	}
	
	public List<String> readLockedFileList(String filePath){
		File lockfile = new File(filePath);
		Scanner sc;
		try {
			sc = new Scanner(lockfile);
		
		List<String> lockedFileList = new ArrayList<String>();
		while(sc.hasNextLine()){
			lockedFileList.add(sc.nextLine());
		}
		sc.close();
		return lockedFileList;
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
		
	public void writeLockedFileList(List<String> lockedFileList){
		try{
		File lockfile = new File(lockFileLocation);
		FileWriter fw = new FileWriter(lockfile, false);
		for(int i = 0; i < lockedFileList.size();i++){
//		for(String lockedFile : lockedFileList){
			if(i + 1 >= lockedFileList.size()){
				fw.write(lockedFileList.get(i));
			}else{
				fw.write(lockedFileList.get(i) + "\n");
			}
		}
		fw.flush();
		fw.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
